
/**
 * AppleIIGo
 * NIB Disk Image class
 * (C) 2008 by Marc S. Ressl (mressl@umich.edu)
 * Released under the GPL
 */

#include <stdio.h>
#include "NIBDiskImage.h"

bool NIBDiskImage::isDiskImageValid(UINT32 diskType,
									UINT32 diskImageByteNum) {
	if (diskType != FLOPPYDISKTYPE_5_25)
		return false;
	
	for (UINT32 index = 35; index <= 40; index++)
		if (diskImageByteNum == (index * NIB_TRACK_BYTENUM))
			return true;
	
	return false;
}

NIBDiskImage::NIBDiskImage(char * diskImagePath,
						   UINT32 diskImageOffset,
						   UINT32 diskImageByteNum,
						   bool isForceWriteProtected) :
NibbleDiskImage(diskImagePath) {
	if (!isDiskImageOpened())
		return;
	
	if (!readDiskImage(diskImageOffset, diskImageByteNum, true))
		return;
	
	if (!allocateDisk())
		return;
	
	if (!readDiskImage(diskImageOffset, diskImageByteNum, false))
		return;
	
	setWriteProtected(isWriteProtected() || isForceWriteProtected);
}

NIBDiskImage::~NIBDiskImage() {
	if (!isDiskImageOpened())
		return;
	
	if (!isModified())
		return;
	
	FDIDiskImage::writeDiskImage(this);
}	

bool NIBDiskImage::readDiskImageTrack(UINT32 diskImageTrackIndex,
									  bool isSetTrackBitNum) {
	UINT8 nibTrackData[NIB_TRACK_BYTENUM];
	
	if (fread(nibTrackData, NIB_TRACK_BYTENUM, 1, diskImageFile) != 1)
		return false;
	
	setTrackIndex(diskImageTrackIndex * 4);
	setHeadIndex(0);
	UINT32 bitNum = writeTrack(nibTrackData,
							   NIB_TRACK_BYTENUM,
							   isSetTrackBitNum);
	if (isSetTrackBitNum)
		setTrackBitNum(bitNum);
	
	return true;
}

bool NIBDiskImage::readDiskImage(UINT32 diskImageOffset,
								 UINT32 diskImageByteNum,
								 bool isSetTrackBitNum) {
	fseek(diskImageFile, diskImageOffset, SEEK_SET);
	UINT32 diskImageTrackNum = diskImageByteNum / NIB_TRACK_BYTENUM;
	
	for (UINT32 index = 0; index < diskImageTrackNum; index++)
		if (!readDiskImageTrack(index, isSetTrackBitNum))
			return false;
	
	return true;
}
